//
//  BSSAddPhotosTableViewCell.m
//  PreschoolEducation
//
//  Created by 李传铎 on 2020/11/14.
//  Copyright © 2020 李传铎. All rights reserved.
//

#import "BSSAddPhotosTableViewCell.h"
#import "BSSPRHomePageCollectionViewCell.h"
#import "UIImageView+WebCache.h"
#import "BSSAddPhotoTwoCollectionViewCell.h"
#import "BBSShowPhotoCollectionViewCell.h"

#import "UIButton+WebCache.h"
#import "BSSUploadImagApi.h"

@interface BSSAddPhotosTableViewCell ()<UINavigationControllerDelegate,UIImagePickerControllerDelegate,UITextFieldDelegate>
@property (nonatomic, strong) UIImagePickerController               *imagePicker;
@end
@implementation BSSAddPhotosTableViewCell

- (void)awakeFromNib {
    [super awakeFromNib];
    // Initialization code
}

-(NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView
{
    return 1;
}
-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
   
    return self.photoArray.count + 1;
    
}
-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.row == self.photoArray.count) {
        static NSString *addItem = @"cell";
        BSSAddPhotoTwoCollectionViewCell *addItemCell = [collectionView dequeueReusableCellWithReuseIdentifier:addItem forIndexPath:indexPath];
        addItemCell.backgroundImageV.image = [UIImage imageNamed:@"pic_add_pic_small"];
        
        return addItemCell;
    }else{
        static NSString *identify = @"cell1";
        BBSShowPhotoCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:identify forIndexPath:indexPath];
        [cell.deleImageBnt addTarget:self action:@selector(deleImageClick:) forControlEvents:UIControlEventTouchUpInside];
        cell.deleImageBnt.tag = 1000 + indexPath.row;
        cell.imageView.image = self.photoArray[indexPath.row];
        return cell;
    }
}

- (void)deleImageClick:(UIButton *)sender{
    NSInteger index = sender.tag - 1000;
    [self.photoArray removeObjectAtIndex:index];
    [self.collectionView reloadData];
   
}
-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.row == self.photoArray.count) {
        [self chooseImge];
    }
    
}
- (void)chooseImge {
    UIAlertController *actionSheetController = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];
    UIAlertAction *action1 = [UIAlertAction actionWithTitle:@"拍照" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {
            self.imagePicker.sourceType = UIImagePickerControllerSourceTypeCamera;
            [[self getCurrentVC] presentViewController:self.imagePicker animated:YES completion:nil];
        }
    }];
    UIAlertAction *action2 = [UIAlertAction actionWithTitle:@"从相册获取" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypePhotoLibrary]) {
            self.imagePicker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
            [[self getCurrentVC] presentViewController:self.imagePicker animated:YES completion:nil];
        }
    }];
    
    UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        
    }];
    
    [actionSheetController addAction:cancelAction];
    [actionSheetController addAction:action1];
    [actionSheetController addAction:action2];
    
    [[self getCurrentVC] presentViewController:actionSheetController animated:YES completion:nil];
}

#pragma mark - UIImagePickerControllerDelegate
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info {
    [picker dismissViewControllerAnimated:YES completion:nil];
    UIImage *image = [info objectForKey:UIImagePickerControllerEditedImage];
    [self.photoArray addObject:image];
    [_collectionView reloadData];
//    [self uploadImage:image];
}
//- (void)uploadImage:(UIImage *)image {
//    [MBProgressHUD showHUD];
//    BSSUploadImagApi *api  = [[BSSUploadImagApi alloc] initWithURL:@"" dic:@{} imageArray:@[image]];
//    api.isFiles = NO;
//    [api startRequest:^(BSSRequestStatus requestStatus, NSString *message, id responseObject) {
//
//        [MBProgressHUD hideHUD];
//        if (requestStatus == BSSRequestStatusSuccess) {
//
//            if (!IsEmpty(responseObject[@"data"])) {
//                NSDictionary *dataDic = [responseObject valueForKey:@"data"];
//                NSString *imageURL = [dataDic valueForKey:@"imageURL"];
//                self.model.value = imageURL;
//                self.licenseDeleteBtn.hidden = NO;
//                [self.licenseBtn sd_setImageWithURL:[NSURL URLWithString:Format(self.model.value)] forState:UIControlStateNormal placeholderImage:[UIImage imageNamed:Format(self.model.placeholderImage)]];
//            }
//
//        }else{
//            [MBProgressHUD showText:message];
//        }
//    }];
//
//}
//获取当前控制器
- (UIViewController *)getCurrentVC{
    UIViewController *rootViewController = [UIApplication sharedApplication].keyWindow.rootViewController;
    UIViewController *currentVC = [self getCurrentVCFrom:rootViewController];
    return currentVC;
    
}
- (UIViewController *)getCurrentVCFrom:(UIViewController *)rootVC{
    UIViewController *currentVC;
    
    if ([rootVC presentedViewController]) {
        // 视图是被presented出来的
        rootVC = [rootVC presentedViewController];
    }
    if ([rootVC isKindOfClass:[UITabBarController class]]) {
        // 根视图为UITabBarController
        currentVC = [self getCurrentVCFrom:[(UITabBarController *)rootVC selectedViewController]];
        
    } else if ([rootVC isKindOfClass:[UINavigationController class]]){
        // 根视图为UINavigationController
        currentVC = [self getCurrentVCFrom:[(UINavigationController *)rootVC visibleViewController]];
        
    } else {
        // 根视图为非导航类
        currentVC = rootVC;
    }
    return currentVC;
}
#pragma  mark UICollectionViewDelegateFlowLayout

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath
{
    
    return CGSizeMake((SCREEN_WIDTH   - 40)/2.0 ,105);
    
}

//定义每个Section的四边间距
-(UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout insetForSectionAtIndex:(NSInteger)section
{
    return UIEdgeInsetsMake(0, 8, 0, 8);//分别为上、左、下、右
}

- (void)setSelected:(BOOL)selected animated:(BOOL)animated {
    [super setSelected:selected animated:animated];
    
    // Configure the view for the selected state
}
- (instancetype)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier {
    self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
    if (self) {
        
        [self creatUI];
    }
    return self;
}
- (void)creatUI{
    [self.contentView addSubview:self.titleLab];
    [self.contentView addSubview:self.textField];
    
    [_titleLab mas_makeConstraints:^(MASConstraintMaker *make) {
           make.left.mas_equalTo(__kSize(22));
           make.top.mas_equalTo(__kSize(12));
       }];
       
    [_textField mas_makeConstraints:^(MASConstraintMaker *make) {
           make.centerY.mas_equalTo(self.contentView);
           make.right.mas_equalTo(__kSize(- 22));
           make.width.mas_equalTo(__kScreenWidth__/2.0);
       }];
    self.backgroundColor = colorCode(@"f2f2f2");
    UIView *diView = [[UIView alloc]init];
    [self.contentView addSubview:diView];
    [diView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(0);
        make.right.mas_equalTo(0);
        make.height.mas_equalTo(105);
        make.top.mas_equalTo(_titleLab.mas_bottom).offset(10);
        make.bottom.mas_equalTo(-12);
    }];
    UICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc]init];
    // 水平方向滑动
    flowLayout.scrollDirection = UICollectionViewScrollDirectionHorizontal;
    
    _collectionView = [[UICollectionView alloc]initWithFrame:CGRectMake(7, 7, SCREEN_WIDTH - 14, 105) collectionViewLayout:flowLayout];

    [diView addSubview:_collectionView];
    
    [_collectionView mas_makeConstraints:^(MASConstraintMaker *make) {
        
    }];
    _collectionView.backgroundColor = [UIColor whiteColor];
    self.collectionView.delegate=self;
    self.collectionView.dataSource=self;
    self.pageControl.numberOfPages= self.photoArray.count/2;
    [_collectionView registerClass:[BSSAddPhotoTwoCollectionViewCell class]forCellWithReuseIdentifier:@"cell"];
    [_collectionView registerClass:[BBSShowPhotoCollectionViewCell class]forCellWithReuseIdentifier:@"cell1"];
    _collectionView.alwaysBounceHorizontal = NO;
    _collectionView.contentInset = UIEdgeInsetsMake(0, -15, 0, 15);
    _collectionView.scrollIndicatorInsets = UIEdgeInsetsMake(0, 0, 0, -2);
    _collectionView.contentSize = CGSizeMake((self.frame.size.width - 40)/2.0  * self.photoArray.count + 20,0);
  
}

- (void)setModel:(BSSEnterpriseCertificationModel *)model{
    _model = model;
    _textField.text = model.value;
}
- (UIImagePickerController *)imagePicker{
    if (!_imagePicker) {
        _imagePicker = [[UIImagePickerController alloc]init];
        _imagePicker.delegate = self;
        _imagePicker.allowsEditing = YES;
        _imagePicker.modalPresentationStyle = UIModalPresentationFullScreen;
    }
    return _imagePicker;
}
- (UILabel *)titleLab {
    if (!_titleLab) {
        _titleLab = [UILabel new];
        _titleLab.textColor = __kColor(51, 51, 51);
        _titleLab.font = _titleLab.font = fontCount(14);;
    }
    return _titleLab;
}
- (UITextField *)textField{
    if (!_textField){
        _textField = [UITextField new];
        _textField.delegate  = self;
        _textField.font = __kFont(14);
        _textField.textColor = colorCode(@"#999999");
        _textField.textAlignment = NSTextAlignmentRight;
        _textField.clearButtonMode = UITextFieldViewModeWhileEditing;
        _textField.autocorrectionType = UITextAutocorrectionTypeNo;
        _textField.placeholder = @"请输入";
    }
    return _textField;
}
- (NSMutableArray *)photoArray{
    if (!_photoArray) {
        _photoArray = [NSMutableArray array];
    }
    return _photoArray;
}
@end
